package indexingSystem;

import java.util.Vector;

public class Cluster {
	private TermFrequencyVector centroid = null;
	private Vector<Document> documents = null;
	private Vector<Document> newSet = null;
	private int vectorSize;
	Cluster (int vectorSize) {
		this.vectorSize = vectorSize;
	}
	private Vector<Double> nullVector() {
		Vector<Double> zero = new Vector<Double>(vectorSize);
		for(int i = 0; i < zero.capacity(); i++)
			zero.set(i, 0.0);
		return zero;
	}
	private void calcCentroid() throws Exception {
		double inv_len = 1 / vectorSize;
		Vector<Double> sum = nullVector();
		for(Document doc : documents)
			sum = doc.getTFV().add(sum);
		for(int i = 0; i < sum.size(); i++)
			sum.set(i, sum.elementAt(i) * inv_len);
		centroid = new TermFrequencyVector(sum);
	}
	public TermFrequencyVector getCentroid() {
		return centroid;
	}
	public Vector<Document> getDocumentSet() {
		return documents;
	}
	public void startUpdate() {
		newSet = new Vector<Document>();
	}
	public boolean endUpdateChanged() throws Exception {
		boolean changed = newSet.equals(documents);
		documents = newSet;
		newSet = null;
		if (changed)
			calcCentroid();
		return changed;
	}
	public void addDocument(Document doc) throws Exception {
		if (newSet == null)
			throw new Exception("Cluster is not enabled to be added documents.");
		newSet.add(doc);
	}
}
